package com.andy.module.uploadphoto

import android.os.Bundle
import com.andy.module.R
import com.andy.module.base.BaseVbFragment
import com.andy.module.databinding.FragmentUploadPhotoBinding
import com.andy.module.ext.initGridDividerLine
import com.andy.module.ext.initGridLayout
import com.andy.module.progress.UploadProgressListener
import com.andy.module.util.DownloadUtil
import com.huantansheng.easyphotos.EasyPhotos
import com.huantansheng.easyphotos.callback.SelectCallback
import com.huantansheng.easyphotos.models.album.entity.Photo

/**
 * @creator:LuoFan
 * @date:2022/6/10
 * @description: 图片上传fragment
 */
open class UploadPhotoFragment : BaseVbFragment<UploadPhotoViewModel, FragmentUploadPhotoBinding>() {

    private lateinit var photoAdapter: UploadPhotoAdapter

    private var spanCount = 3

    var uploadUrl = ""

    var maxChooseCount = 5

    override fun initView(savedInstanceState: Bundle?) {
        photoAdapter = UploadPhotoAdapter()
        initRecycler()
    }

    private fun initRecycler() {
        mViewBind.photoRecycler.initGridLayout(spanCount)
        mViewBind.photoRecycler.initGridDividerLine(count = 3)
        mViewBind.photoRecycler.adapter = photoAdapter
        initAdapterChildClick()
        photoAdapter.addEmptyPhoto()
    }

    private fun initAdapterChildClick() {
        photoAdapter.setOnItemChildClickListener { _, view, position ->
            when (view.id) {
                R.id.img_photo -> {
                    //跳转到查看图片
                }
                R.id.img_add -> {
                    chooseImage(position)
                }
                R.id.img_retry -> {

                }
                R.id.img_delete -> {
                    if (photoAdapter.itemCount == maxChooseCount) {
                        photoAdapter.removeAt(position)
                        photoAdapter.addEmptyPhoto()
                    } else {
                        photoAdapter.removeAt(position)
                    }
                }
            }
        }
    }

    private fun getChooseCount(): Int {
        var size = 0
        photoAdapter.data.forEach {
            if (it.localPath.isNotEmpty() || it.photoUrl.isNotEmpty()) {
                size++
            }
        }
        return maxChooseCount - size
    }

    private fun chooseImage(position: Int) {
        EasyPhotos.createAlbum(this, true, false, GlideEngine.getInstance())
            .setCount(getChooseCount())
            .start(object : SelectCallback() {
                override fun onResult(photos: ArrayList<Photo>, isOriginal: Boolean) {
                    //如果需要压缩可以在这里处理
                    uploadPhoto(photos, position)
                }

                override fun onCancel() {

                }
            })
    }

    private fun uploadPhoto(photos: ArrayList<Photo>, position: Int) {
        photoAdapter.removeAt(position)
        photos.forEachIndexed { index, photo ->
            val params = HashMap<String, String>()
            params["type"] = "1"
            DownloadUtil.upload(uploadUrl, photo.path, params, object : UploadProgressListener {
                override fun onUploadSuccess(url: String) {
                    mViewBind.root.post {
                        photoAdapter.updateItemSuccessByPath(photo.path, url)
                    }
                }

                override fun onError(error: Throwable) {
                    mViewBind.root.post {
                        photoAdapter.updateItemErrorByPath(photo.path)
                    }
                }

                override fun onChanged(current: Long, total: Long, percent: Double) {
                    photoAdapter.updateItemProgressByPath(photo.path, percent)
                }
            })
            photoAdapter.addUploadingPhoto(photo.path, index + position)
        }
        if (photoAdapter.itemCount < maxChooseCount) {
            photoAdapter.addEmptyPhoto()
        }
    }

    fun resetAdapter(adapter: UploadPhotoAdapter) {
        photoAdapter = adapter
        initRecycler()
    }

    fun setGridSpanCount(count: Int) {
        spanCount = count
        mViewBind.photoRecycler.initGridLayout(count)
    }
}


